package network.t_02_nio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NIOClient {
    public static void main(String[] args) {
        try (SocketChannel socketChannel = SocketChannel.open();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            // socketChannel.configureBlocking(false); // 设置非阻塞
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 6666));
            // while (!socketChannel.finishConnect()) continue;

            for (int i = 0; i <= 9999999; i++) baos.write(("，Hello：" + i).getBytes(StandardCharsets.UTF_8));
            ByteBuffer buffer = ByteBuffer.allocate(5 + baos.toByteArray().length); // 5 = 1(type) + 4(length)
            buffer.put((byte) 9);
            buffer.putInt(baos.toByteArray().length);
            buffer.put(baos.toByteArray());
            buffer.flip();
            while (buffer.hasRemaining()) socketChannel.write(buffer);
            System.out.println("发送完毕");

            buffer = ByteBuffer.allocate(5);
            while (buffer.hasRemaining()) socketChannel.read(buffer);
            buffer.flip();
            buffer.get();
            buffer = ByteBuffer.allocate(buffer.getInt());
            while (buffer.hasRemaining()) socketChannel.read(buffer);
            buffer.flip();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            System.out.println(new String(bytes, StandardCharsets.UTF_8) + "\n收到数据");

            // Selector selector = Selector.open();
            // socketChannel.register(selector, SelectionKey.OP_CONNECT);
            // while (true) {
            //     selector.select();
            //     Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            //     while (keyIterator.hasNext()) {
            //         SelectionKey key = keyIterator.next();
            //         keyIterator.remove();
            //         if (key.isConnectable()) {
            //             SocketChannel channel = (SocketChannel) key.channel();
            //             // 如果正在连接，则完成连接
            //             if (channel.isConnectionPending()) while (!channel.finishConnect()) continue;
            //             System.out.println("连接成功！");
            //             // 连接成功后，可以写入或读取数据
            //             key.cancel(); // 取消选择键的注册
            //         }
            //     }
            // }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}